import abc
import time

import coin.exchange.base.kr_rest.rest_client_base as rcb
from coin.exchange.util.rate_limit import RateLimiter


class NativePrivateClientBase(rcb.RestClientBase):
  __metaclass__ = abc.ABCMeta

  def __init__(self, *, url, timeout=1, rate_limit_rate=3.0, rate_limit_time=1.0):
    self.url = url
    self.rate_limit = RateLimiter(rate_limit_rate, rate_limit_time)
    self.timeout = timeout

  @abc.abstractmethod
  def _query_impl(self, endpoint, params=None):
    raise NotImplementedError()

  def _query_nocheck(self, endpoint, params=None):
    req_timestamp = time.time()
    content = self._query_impl(endpoint, params=params)
    res_timestamp = time.time()
    return rcb.RestUpdate(req_timestamp, res_timestamp, content)

  def _query(self, endpoint, params=None, disable_rate_limit=False):
    if not disable_rate_limit:
      while not self.rate_limit.check():
        time.sleep(0.1)
    else:
      self.rate_limit.check()
    return self._query_nocheck(endpoint, params=params)
